package com.dangz.dans.utils;

import okhttp3.*;
import okhttp3.internal.framed.Header;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.Map;

/**
 * okHttp请求封装
 * @author dangz
 * @since 2018/3/15 16:08
 */
public class OkHttpHader {
    private static OkHttpClient client = null;

    private OkHttpHader() {}

    public static OkHttpClient getInstance() {
        if (client == null) {
            synchronized (OkHttpHader.class) {
                if (client == null)
                    client = new OkHttpClient();
            }
        }
        return client;
    }

    /**
     * Get请求
     * @param url
     */
    public static String doGet(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();
        Response response = getInstance().newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * Post请求发送键值对数据
     * @param url
     */
    public static String doPostForMap(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        Headers.Builder header = new Headers.Builder();
        if (headers != null) {
            header = getHeaders(headers, header);
        }
        Request request = new Request.Builder().url(url).headers(header.build()).post(builder.build()).build();
        Response response = getInstance().newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    private static Headers.Builder getHeaders(Map<String, String> headers, Headers.Builder headerBuilder){
        for (String key : headers.keySet()) {
            headerBuilder.add(key, headers.get(key));
        }
        return headerBuilder;
    }

    /**
     * Post请求发送JSON数据
     * @param url
     * @param jsonParams
     */
    public static String doPostForJosn(String url, Map<String, String> headers, String jsonParams) throws IOException {
        if (StringUtils.isEmpty(jsonParams)) {
            jsonParams = "";
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8")
                , jsonParams);
        Headers.Builder header = new Headers.Builder();
        if (headers != null) {
            header = getHeaders(headers, header);
        }
        Request request = new Request.Builder()
                .url(url)
                .headers(header.build())
                .post(body)
                .build();
        Response response = getInstance().newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * 上传文件
     * @param url
     * @param pathName
     * @param fileName
     */
    public static Boolean doFile(String url, String pathName, String fileName) throws IOException {
        Boolean sucess = false;
        //判断文件类型
        MediaType MEDIA_TYPE = MediaType.parse(judgeType(pathName));
        //创建文件参数
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(MEDIA_TYPE.type(), fileName,
                        RequestBody.create(MEDIA_TYPE, new File(pathName)));
        //发出请求参数
        Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + "9199fdef135c122")
                .url(url)
                .post(builder.build())
                .build();
        Response response = getInstance().newCall(request).execute();
        if (response.isSuccessful()) {
            sucess = true;
        } else {
            throw new IOException("Unexpected code " + response);
        }
        return sucess;
    }

    /**
     * 根据文件路径判断MediaType
     * @param path
     * @return
     */
    private static String judgeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    /**
     * 下载文件
     * @param url
     * @param fileDir
     * @param fileName
     */
    public static void downFile(String url, final String fileDir, final String fileName) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    File file = new File(fileDir, fileName);
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (is != null) is.close();
                    if (fos != null) fos.close();
                }
            }
        });
    }

    /*如果在下载文件中需要进度的话，可以修改onResponse回调里面的内容就可以获取进度
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        InputStream is = null;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null;
        try {
            is = response.body().byteStream();
            File file = new File(fileDir, fileName);
            fos = new FileOutputStream(file);
            //---增加的代码---
            //计算进度
            long totalSize = response.body().contentLength();
            long sum = 0;
            while ((len = is.read(buf)) != -1) {
                sum += len;
                //progress就是进度值
                int progress = (int) (sum * 1.0f/totalSize * 100);
                //---增加的代码---
                fos.write(buf, 0, len);
            }
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) is.close();
            if (fos != null) fos.close();
        }
    }*/
}
